package cn.com.ry.framework.monitormeter.instrument.binder;

import cn.com.ry.framework.monitormeter.metric.mq.MqConsumerBean;
import cn.com.ry.framework.monitormeter.metric.mq.rocketmq.AliRocketMqMetrics;
import cn.com.ry.framework.monitormeter.metric.mq.rocketmq.ApacheRocketMqMetrics;
import io.micrometer.core.instrument.MeterRegistry;

import java.util.ArrayList;
import java.util.List;

public class MQMonitor {

    private String name;
    private String nameserver;
    private List<MqConsumerBean> mqConsumerBeanList = new ArrayList<MqConsumerBean>();

    public MQMonitor(String name, String nameserver) {
        this.name = name;
        this.nameserver = nameserver;
    }


    public MQMonitor topic(String topic, String consumerGroup) {
        //去重
        for (MqConsumerBean mqConsumerBean : mqConsumerBeanList) {
            if (mqConsumerBean.getTopic().equals(topic) && mqConsumerBean.getConsumerGroup().equals(consumerGroup)) {
                return this;
            }
        }
        MqConsumerBean mqConsumerBean = new MqConsumerBean(topic, consumerGroup);
        mqConsumerBeanList.add(mqConsumerBean);
        return this;
    }


    public void buildMqMetrics(MeterRegistry meterRegistry) {
        if (mqConsumerBeanList != null && mqConsumerBeanList.size() > 0) {
            try {
                //优先匹配apache rocketmq
                Class.forName("org.apache.rocketmq.tools.admin.DefaultMQAdminExt");
                new ApacheRocketMqMetrics(name, nameserver, mqConsumerBeanList).bindTo(meterRegistry);
            } catch (ClassNotFoundException e) {
                //在匹配alibaba rocketmq
                try {
                    Class.forName("com.alibaba.rocketmq.tools.admin.DefaultMQAdminExt");
                    new AliRocketMqMetrics(name, nameserver, mqConsumerBeanList).bindTo(meterRegistry);
                } catch (ClassNotFoundException e1) {

                }
            }
        }
    }

}
